let differMass=null;
let airCorrected=null;
let standardWeightCorrected=null;
let massTolerance=null;
let magneticTolerance=null;
let polarizationTolerance=null;


let massCorrected=null;
let magneticReads=null;
let polarizationReads=null;

layui.use(['form','jquery'], function () {
    let form = layui.form;
    let $ = layui.jquery;
    let MODULE_PATH = rootPath + "/ScaletabController";
    let loader = layer.load();

    $('#tdsmw').text(document.getElementById('smw').value);


    /*查询当前系统正在使用的串口*/
    var recom = selectSerials();
    if(recom == null){
        layer.msg('没有找到可用的串口', {icon: 2, time: 1000});
        layer.close(loader);
        return;
    }else{
        //打开串口
        var returnOpenSerial = openOrCloseSerial(recom,true);
        layer.msg(returnOpenSerial, {icon: 0, time: 1000});
        layer.close(loader);
    }

    //保存
    form.on('submit(scaletab-save)', function (data) {
        let loader = layer.load();

        data.field.differMass=differMass;
        data.field.massCorrected=massCorrected;

        data.field.standardWeightCorrected=standardWeightCorrected;
        data.field.massTolerance=massTolerance;
        data.field.magneticTolerance=magneticTolerance;
        data.field.polarizationTolerance=polarizationTolerance;
        getTdText();

        data.field.airCorrected=airCorrected;
        data.field.magneticReads=magneticReads;
        data.field.polarizationReads=polarizationReads;

        $.ajax({
            url: MODULE_PATH+'/add',
            data: data.field,
            dataType: 'json',
            contentType: 'application/x-www-form-urlencoded',
            type: 'post',
            success: function (result) {
                if (result.code==200) {
                    layer.msg(result.msg, {icon: 1, time: 1000}, function () {
                        localStorage.setItem('shouldRefresh', 'true');
                        history.back();
                    });
                } else {
                    layer.msg(result.msg, {icon: 2, time: 1000});
                    layer.close(loader);
                }
            }
        })
        return false;
    });
});

function finish() {
    let array = serialSaveInfo;
    let myArray  = [];//计算
    let loader = layer.load();
    for (let i = 0; i < array.length; i++) {

        const trimmedStr = array[i].trimEnd();
        const arr = trimmedStr.split(/\s+/);
        const thirdElement = arr[2];
        //单位换算
        let value=parseFloat(thirdElement) * 1000
        myArray[i]=value;
    }

    // 缓存DOM对象，减少重复查询
        const $read1Input = $('#read1');
    // 使用join明确指定分隔符，比toString()更可控
        $read1Input.val(myArray.join(','));
    // 遍历数组并渲染到对应TD
    myArray.forEach((value, index) => {
        // 计算组号(1或2)和组内序号(1-4)
        const group = Math.floor(index / 4) + 1;
        const position = (index % 4) + 1;

        // 只处理前8条数据(2组×4条)
        if (group > 2) {
            // 超出范围时仅提示一次
            if (index === 8) {
                layer.msg(`数据超出最大限制（${myArray.length}条），仅处理前8条`, {
                    icon: 2,
                    time: 2000
                });
                layer.close(loader);
            }
            return;
        }

        // 拼接选择器并渲染
        const tdSelector = `#read${group}${position}`;
        const $td = $(tdSelector);

        if ($td.length) {
            $td.text(value);
        } else {
            console.warn(`未找到DOM元素: ${tdSelector}`);
        }
    });




    //获取预设值
    const select = document.getElementById("yzz");
    const smwValue = document.getElementById("smw").value;
    const mpeValue = document.getElementById("mpe").value;
    const combinedValue = smwValue + mpeValue;
    const key = combinedValue; // 目标key（选项的value）
    const text = getOptionTextByValue(select, key);
    console.log(`key为"${key}"的选项文本：`, text); // 输出："XML格式
    if (!text ) {
        layer.msg('请先配置预设修正值', {icon: 1, time: 1000});
        layer.close(loader);
        return;
    }

    const kv = JSON.parse(text);
    //预设值
    $('#standardWeightCorrected').text(kv.v1);
    $('#magneticTolerance').text(kv.v2);
    $('#massTolerance').text(kv.v3);
    $('#polarizationTolerance').text(kv.v4);
    standardWeightCorrected=kv.v1;
    magneticTolerance=kv.v2;
    massTolerance=kv.v3;
    polarizationTolerance=kv.v4;

    //相差质量
    // 执行ABBA
    //数据解析 赋值
    if(myArray.length>4){
        let value1 = myArray[1] + myArray[2] - myArray[0] - myArray[3];
        let value2 = myArray[5] + myArray[6] - myArray[4] - myArray[7];
        let result = (value1 + value2) / 4;
        $('#differMass').text(result);//相差质量
        differMass=result;
        let sum_st_diff = Number(kv.v1) + Number(result);
        $('#massCorrected').text(sum_st_diff);
        massCorrected=sum_st_diff;
    }else{
        let value1 = myArray[1] + myArray[2] - myArray[0] - myArray[3];
        let result = value1 / 2;
        $('#differMass').text(result);//相差质量
        differMass=result;
        let sum_st_diff = Number(kv.v1) + Number(result);
        $('#massCorrected').text(sum_st_diff);
        massCorrected=sum_st_diff;
    }
    //
    const button = document.getElementById('mysubmit');
    button.removeAttribute('disabled'); // 修改按钮状态
    button.classList.remove('disabled');

    openOrCloseSerial('COM1',false);
    layer.close(loader);
}
function getTdText() {
    // 根据 id 获取 td 元素
    const tdairCorrected = document.getElementById('airCorrected');
    const TDmagneticReads = document.getElementById('magneticReads');
    const tdpolarizationReads = document.getElementById('polarizationReads');
    if (tdairCorrected) {
        // 获取 td 元素的文本内容
        airCorrected = tdairCorrected.textContent;
    }
    if (TDmagneticReads) {
        magneticReads = TDmagneticReads.textContent;
    }
    if (tdpolarizationReads) {
        polarizationReads = tdpolarizationReads.textContent;
    }
}
function getOptionTextByValue(select, targetKey) {
    if (!select || !targetKey) return null;

    for (let i = 0; i < select.options.length; i++) {
        const option = select.options[i];
        // 以option的value作为key进行匹配
        if (option.text === targetKey) {
            return option.value; // 返回对应的文本
        }
    }
    return null; // 未找到匹配项
}